using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Abp;
using Abp.Extensions;
using Abp.Notifications;
using Abp.Timing;
using Abp.Web.Security.AntiForgery;
using OplugFramework.Controllers;
using OplugFramework.Portal;
using Microsoft.AspNetCore.Http;

namespace OplugFramework.Web.Host.Controllers
{
    public class HomeController : OplugFrameworkControllerBase
    {
        private readonly INotificationPublisher _notificationPublisher;
        private IAttachmentAppService _iAttachmentAppService;

        public HomeController(
             IAttachmentAppService iAttachmentAppService,
            INotificationPublisher notificationPublisher)
        {
            _notificationPublisher = notificationPublisher;
            _iAttachmentAppService = iAttachmentAppService;
        }

        public IActionResult Index()
        {
            return Redirect("/swagger");
        }

        /// <summary>
        /// This is a demo code to demonstrate sending notification to default tenant admin and host admin uers.
        /// Don't use this code in production !!!
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task<ActionResult> TestNotification(string message = "")
        {
            if (message.IsNullOrEmpty())
            {
                message = "This is a test notification, created at " + Clock.Now;
            }

            var defaultTenantAdmin = new UserIdentifier(1, 2);
            var hostAdmin = new UserIdentifier(null, 1);

            await _notificationPublisher.PublishAsync(
                "App.SimpleMessage",
                new MessageNotificationData(message),
                severity: NotificationSeverity.Info,
                userIds: new[] { defaultTenantAdmin, hostAdmin }
            );

            return Content("Sent notification: " + message);
        }

        [HttpGet]
        public async Task<ActionResult> GetImageAsync(string sysRowId)
        {
            var result = _iAttachmentAppService.GetFileCache(sysRowId);
            if (result == null)
                result = await _iAttachmentAppService.GetFileAsync(sysRowId);
            return File(result, @"image/jpeg"); //application/pdf
        }
        [HttpPost]
        public async Task<IActionResult> UploadFilesAsync(
            IFormFile[] files,
            string objectId = "",
            string objectName = "",
            string objectField = "")
        {
            var result = await _iAttachmentAppService.UploadFiles(files, objectId, objectName, objectField);
            return Ok(result);
        }
    }
}
